package com.ctgu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ctgu.common.ResponseResult;
import com.ctgu.mapper.CompanyMapper;
import com.ctgu.model.vo.EmployeeVo;
import com.ctgu.model.entity.*;
import com.ctgu.mapper.EmployeeMapper;
import com.ctgu.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.utils.RedisCache;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yiMa
 * @since 2023-07-05
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    private IPositionService positionService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IExperienceService experienceService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public ResponseResult getEmployeeOne(Integer id) {
        if(id==null){
            return new ResponseResult<>(200,"成功", SecurityContextHolder.getContext().getAuthentication());
        }
        return new ResponseResult(200,"成功",getById(id));
    }

    @Override
    public ResponseResult getList(int page, int pageSize, String name,Integer depId) {
        LoginUser loginUser=(LoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //分页构造器
        Page pageInfo=new Page(page,pageSize);
//        String key="employee"+"-"+loginUser.getUser().getId()+"-"+depId;
        List<EmployeeVo> list=null;
//        list=(List<EmployeeVo>) redisCache.getCacheObject(key);
//        if(list!=null){
//            pageInfo.setRecords(list);
//            return new ResponseResult<>(200,"查询成功",pageInfo);
//        }
        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.eq(depId!=null,Employee::getDepId,depId);
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        if(loginUser.getUser().getRoleId().equals("4")){
            queryWrapper.eq(Employee::getCompanyId,loginUser.getUser().getId());
        }
        //添加排序条件
        queryWrapper.orderByAsc(Employee::getBirthday);
        //执行查询
        this.page(pageInfo,queryWrapper);
        Page<EmployeeVo> dtoPage=new Page<>();
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Employee> records=pageInfo.getRecords();
        //做处理，把did，和pid转换为相应的部门名和职位名字;
        list=records.stream().map((item)->{
            EmployeeVo employeeVo =new EmployeeVo();
            BeanUtils.copyProperties(item, employeeVo);
            employeeVo.setDeptName(departmentService.getById(item.getDepId()).getName());
            employeeVo.setCompanyName(companyMapper.selectById(item.getCompanyId()).getCompanyName());
            employeeVo.setPosName(positionService.getById(item.getPosId()).getName());
            return employeeVo;
        }).collect(Collectors.toList());
        dtoPage.setRecords(list);
        //redisCache.setCacheObject(key,list,120, TimeUnit.MINUTES);
        return new ResponseResult<>(200,"分页成功",dtoPage);
    }

    @Override
    public ResponseResult register(Employee employee) {
        Integer integer = registrationRules(employee);
        switch (integer){
            case 0: return new ResponseResult<>(400,"用户名已经存在重新输入");
            case 1: return new ResponseResult<>(400,"该身份证已经注册重新输入");
            case 2: return new ResponseResult<>(400,"该邮箱已经注册重新输入");
            case 3: return new ResponseResult<>(400,"该手机已经注册重新输入");
        }
        employee.setPassword(passwordEncoder.encode(employee.getPassword()));
        save(employee);
        return new ResponseResult<>(200,"注册成功");
    }

    //根据人才id查询人才信息
    public Employee getEmpById(Integer empId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",empId);
        return this.getOne(queryWrapper);
    }

    //hr查看非在职人员
    public ResponseResult getDepartList(int page,int pageSize,String name){
        //分页构造器
        Page pageInfo=new Page(page,pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.eq(Employee::getWorkState,"离职");
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加排序条件
        queryWrapper.orderByAsc(Employee::getBirthday);
        //执行查询
        this.page(pageInfo,queryWrapper);
        Page<Employee> dtoPage=new Page<>();
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Employee> records=pageInfo.getRecords();
        //做处理，把did，和pid转换为相应的部门名和职位名字;
//        List<EmployeeVo> list=records.stream().map((item)->{
//            EmployeeVo employeeVo =new EmployeeVo();
//            BeanUtils.copyProperties(item, employeeVo);
//            employeeVo.setDeptName(departmentService.getById(item.getDId()).getName());
//            employeeVo.setPosName(positionService.getById(item.getPosId()).getName());
//            return employeeVo;
//        }).collect(Collectors.toList());
        dtoPage.setRecords(records);
        return new ResponseResult<>(200,"分页成功",dtoPage);
    }



    @Override
    @Transactional
    public ResponseResult addCompany(Employee employee) {
        Integer integer = registrationRules(employee);
        switch (integer){
            case 0: return new ResponseResult<>(400,"用户名已经存在重新输入");
            case 1: return new ResponseResult<>(400,"该身份证已经注册重新输入");
            case 2: return new ResponseResult<>(400,"该邮箱已经注册重新输入");
            case 3: return new ResponseResult<>(400,"该手机已经注册重新输入");
        }
        employee.setStatus("1");
        Random random=new Random();
        String userName=employee.getName()+String.valueOf(random.nextInt(1000));
        employee.setUserName(userName);
        String password = passwordEncoder.encode("1234");
        employee.setPassword(password);
        employee.setBeginDate(LocalDate.now());
        LoginUser loginUser=(LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer companyId = loginUser.getUser().getId();
        Company company=(Company) loginUser.getUser();
        employee.setCompanyId(companyId);
        employee.setWorkState("在职");
        save(employee);
        Experience experience=new Experience();
        experience.setDateOfEmployment(LocalDateTime.now());
        LambdaQueryWrapper<Employee> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUserName,userName);
        Employee employee1=getOne(wrapper);
        experience.setEId(employee1.getId());
        LambdaQueryWrapper<Position> wrapper1=new LambdaQueryWrapper<>();
        Position position = positionService.getById(employee.getPosId());
        experience.setDuties(position.getName());
        experience.setCompanyName(company.getCompanyName());
        experience.setWorkAddr(company.getCompanyAddr());
        experienceService.save(experience);
        return new ResponseResult<>(200,"添加成功");
    }

    @Override
    public ResponseResult moveEmployee(int id, int toDepId, int toPositionId) {
        Employee employee = getEmpById(id);
        //修改员工表
        employee.setDepId(toDepId);
        employee.setPosId(toPositionId);
        saveOrUpdate(employee);
        return new ResponseResult(200,"调动成功",employee);
    }

    //更新个人信息
    public ResponseResult updateEmpInfo(Employee employee){
        LoginUser loginUser=(LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int id=loginUser.getUser().getId();
        Employee employee1=getById(id);
        if(!employee1.getUserName().equals(employee.getUserName())){
            LambdaQueryWrapper<Employee> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(Employee::getUserName,employee.getUserName());
            Employee one = getOne(wrapper);
            if(Objects.nonNull(one)){
                return new ResponseResult<>(400,"用户名已经存在重新输入");
            }
        }
        if(!employee1.getEmail().equals(employee.getEmail())){
            LambdaQueryWrapper<Employee> wrapper1=new LambdaQueryWrapper<>();
            wrapper1.eq(Employee::getEmail,employee.getEmail());
            Employee one = getOne(wrapper1);
            if(Objects.nonNull(one)){
                return new ResponseResult<>(400,"邮箱已经存在重新输入");
            }
        }
        if(!employee1.getPhone().equals(employee.getPhone())){
            LambdaQueryWrapper<Employee> wrapper2=new LambdaQueryWrapper<>();
            wrapper2.eq(Employee::getPhone,employee.getPhone());
            Employee one = getOne(wrapper2);
            if(Objects.nonNull(one)){
                return new ResponseResult<>(400,"手机号已经存在重新输入");
            }
        }
        employee.setId(id);
        if(employee.getPassword()!=null&&employee.getPassword().length()!=0){
            String password = employee.getPassword();
            password=passwordEncoder.encode(password);
            employee.setPassword(password);
        }
        final CopyOptions copyOptions = CopyOptions.create();
        copyOptions.setOverride(false);
        copyOptions.setIgnoreNullValue(true);
        BeanUtil.copyProperties(employee1,employee, copyOptions);
        updateById(employee);
        return new ResponseResult<>(200,"更新成功");
    }

    public Integer registrationRules(Employee employee){
        LambdaQueryWrapper<Employee> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUserName,employee.getUserName());
        Employee one = getOne(wrapper);
        if(Objects.nonNull(one)){
            return 0;
        }
        wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getIdCard,employee.getIdCard());
        one = getOne(wrapper);
        if(Objects.nonNull(one)){
            return 1;
        }
        wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getEmail,employee.getEmail());
        one = getOne(wrapper);
        if(Objects.nonNull(one)){
            return 2;
        }
        wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getPhone,employee.getPhone());
        one = getOne(wrapper);
        if(Objects.nonNull(one)){
            return 3;
        }
        return 4;
    }
}
